package com.ssyc.common.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SPUtil {

    /**
     * 项目的首选项名称
     */
    public static final String PROJECTNAME = "com.ycss.jpstar";

    /**
     * 获取SharedPreferences
     *
     * @param context
     * @return
     */

    public static SharedPreferences getSharedPreference(Context context) {
        SharedPreferences sp = context.getSharedPreferences(PROJECTNAME, Context.MODE_PRIVATE);
        return sp;
    }

    /**
     * 从SharedPreferences获取String值
     *
     * @param context
     * @param key
     * @return
     */
    public static String getString(Context context, String key) {
        SharedPreferences sp = getSharedPreference(context);
        String decsome = sp.getString(key, "");


        String result = null;
        try {
            result = AESOperator.getInstance().decrypt(decsome);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 从SharedPreferences获取int值
     *
     * @param context
     * @param key
     * @return
     */
    public static int getInt(Context context, String key) {
        SharedPreferences sp = getSharedPreference(context);
        int result = sp.getInt(key, 0);
        return result;
    }

    /**
     * 从SharedPreferences获取boolean值
     *
     * @param context
     * @param key
     * @return
     */
    public static boolean getBoolean(Context context, String key) {
        SharedPreferences sp = getSharedPreference(context);
        boolean result = sp.getBoolean(key, false);
        return result;
    }

    /**
     * 存储数据到SharedPreferences中,仅限于String,Integer,Boolean三种数据类型
     *
     * @param context
     * @param key
     * @param value
     */
    public static void put(Context context, String key, Object value) {
        SharedPreferences sp = getSharedPreference(context);
        Editor editor = sp.edit();

        if (value instanceof String) {

            String encsome = null;
            try {
                encsome = AESOperator.getInstance().encrypt((String)value);
            } catch (Exception e) {
                e.printStackTrace();
            }

            editor.putString(key,encsome);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        }

        editor.commit();
    }

}
